 <?php

/*
  web2printer
  Module     		   : web2printer.php
  License			   : pos-x
  Version    		   : 5
  Reference Plattform: 5
  
  Copyright [1998, 2013] [Oliver Dornauf, pda-systems.COM]

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License. 
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

include ("configuration.php");
	
	class web2printer5 {
		//  start time
		private $timingStart = "";
		// url to filename to process
		private $urlToPrint = "";
		// file content
		private $content = "";
		// host name
		private $scripthost = "";
		// image processing flag
		private $clearImages = 0;
		// array with hyperlinks
		private $links = Array ( );
		// number of links
		private $linkCount = 0;
		// array with images
		private $images = Array ( );
		// number of images
		private $imageCount = 0;
		// hyperlink processing flag
		private $resolveLink = 0;
		// send a E-Mail
		private $email = 0;
		// send a E-Mail stage
		private $stage = 1;
		// array with hyperlinks
		// array with parsed meta tags
		private $metaTags = Array ( );
		// number of parsed meta tags
		private $metaCount = 0;
		// copyright string parsed from meta tags
		private $copyright = "";
		// meta tag processing flag
		private $preserveMetaTags = 0;
		// stylsheet name string
		// empty or not set: stylsheet informations supressed
		// otherwise	   : stylsheet used for printing
		private $stylesheet = "";
		// page title
		private $title = "";
		// original page
		private $authentyPage = "";
		private $web2printerVersion = "<strong>web2printer 5</strong>";
		
		function __construct() {
			global $pageUrlHeader;
			global $pageXRefURLHeader;
			global $pageXRefImages;
			global $activeLinks;
			global $footer;
			global $customFooter;
			
			if (! isset ( $pageUrlHeader )) {
				self::$pageUrlHeader = "<b>This page URL</b>:<br>";
			}
			if (! isset ( $pageXRefURLHeader )) {
				self::$pageXRefURLHeader = "<b>Links:</b>";
			}
			if (! isset ( $pageXRefImages )) {
				self::$pageXRefImages = "<b>Images:</b>";
			}
			if (! isset ( $activeLinks )) {
				self::$activeLinks = 0;
			}
			if (! isset ( $footer )) {
				self::$footer = 1;
			}
			if ($footer == 2 && ! isset ( $customFooter )) {
				self::$customFooter = "please define a footer";
			}
		}
		
		function run() {
			$this->getArgs ();
			$this->prepare (); // format
			if ($this->$stage == 1) {
				$this->display ();
			} else {
				$this->sendMail (); // display or send as e-mail
			}
		}
		
		function getArgs() {
			// start from here :-)
			$this->timingStart = explode ( ' ', microtime () );
			
			if (isset ( $_GET ["img"] )) {
				$this->clearImages = filter_var ( $_GET ["img"], FILTER_VALIDATE_INT );
			}
			
			if (isset ( $_GET ["lnk"] )) {
				$this->resolveLink = filter_var ( $_GET ["lnk"], FILTER_VALIDATE_INT );
			}
			if (isset ( $_GET ["tgs"] )) {
				$this->preserveMetaTags = filter_var ( $_GET ["tgs"], FILTER_VALIDATE_INT );
			}
			if (isset ( $_GET ["style"] )) {
				$this->stylesheet = filter_var ( $_GET ["style"], FILTER_VALIDATE_STRING );
			}
			
			// Process the filename
			// if we nether not have an referer nor an http get -> error
			

			if (isset ( $_SERVER ["HTTP_REFERER"] )) {
				$this->page = filter_var ( $_SERVER ["HTTP_REFERER"], FILTER_VALIDATE_URL );
			} else {
				if (isset ( $_ENV ["HTTP_REFERER"] )) {
					$this->page = filter_var ( $_ENV ["HTTP_REFERER"], FILTER_VALIDATE_URL );
				} else {
					$this->page = "";
				}
			}
			// 
			if ($this->page != "") {
				$this->page = parse_url ( $page, PHP_URL_PATH );
			}
			
			if ($this->page . length == 0) {
				$this->page = $GLOBALS ['defaultPage'];
			}
			if ($this->page [0] != '/') {
				$this->$page = "/" . $this->page;
			}
			$this->urlToPrint = apache_getenv ( 'DOCUMENT_ROOT' ) . $this->page;
		}
	}
	
	function get_current() {
		$stop_time = explode ( ' ', microtime () );
		$current = $stop_time [1] - $this->timingStart [1];
		$current += $stop_time [0] - $this->timingStart [0];
		return sprintf ( "%.6f seconds", $current );
	}
	
	// convert an local filename to uri
	function makeUrl($input) {
		
		$retval = "";
		$input = strtr ( $input, "\\", "/" );
		$input = str_replace ( apache_getenv ( 'DOCUMENT_ROOT' ), "", $input );
		$tokens = parse_url ( $input );
		if (isset ( $tokens ["host"] )) {
			$retval = $input;
		} else {
			$input = str_replace ( apache_getenv ( 'SITE_NAME' ), "", $input );
			$retval = apache_getenv ( 'SERVER_NAME' ) . (($input {0} == '/') ? "" : "/") . $input;
		}
		return $retval;
	}
	
	// prepare the file content
	function prepare() {
				
		if (! is_readable ( $this->urlToPrint )) {
			die ( "could not open:" . $this->urlToPrint );
		}
		$plainFile = file_get_contents ( $this->urlToPrint );
		
		if (! isset ( $plainFile ) || $plainFile == "") {
			die ( "could not read:" . $this->urlToPrint );
		}
		// preserve title tag
		

		if (preg_match ( "/(<title>)(.*)<\\/title>/i", $plainFile, $regs )) {
			$title = trim ( $regs [2] );
			if ($title == "") {
				$title = "web2printer generated file";
			}
		}
		
		if ($this->email == 1) {
			if ($this->stage == 1) {
				$this->content = insertForm ( $plainFile );
				return;
			}
			$this->authentyPage = $plainFile;
		}
		
		// parse copyright
		

		if (preg_match ( "/<meta([ ]?)*name([ ]?)*\\=([ ]?)*\"copyright\"([ ]?)*content([ ]?)*\\=([ ]?)*\"([^\"])*\"/i", $plainFile, $regs )) {
			$this->copyright = preg_replace ( "/<meta([ ]?)*name([ ]?)*\\=([ ]?)*\"copyright\"([ ]?)*content([ ]?)*\\=([ ]?)*\"/i", "", $regs [0] );
			$this->copyright = substr ( $copyright, 0, strpos ($this->copyright, "\"" ) );
		}
		
		getMeta ( $plainFile );
		
		// clean up embedded styles
		$plainFile = preg_replace ( "/style[ ]*=\"[^\"]*\"/i", "", $plainFile );
		
		// cut off header
		$plainFile = preg_replace ( "/<(\\/)?head[ ]*>/i", "<CUTOFFHEADER>", $plainFile );
		$start = strpos ( $plainFile, "<CUTOFFHEADER>" );
		if ($start) {
			$end = strpos ( $plainFile, "<CUTOFFHEADER>", $start + 1 );
			if ($end && $end > 0) {
				$left = substr ( $plainFile, 0, $start );
				$right = substr ( $plainFile, $start + $end + 15 );
				$plainFile = $left . $right;
			} else {
				die ( "unbalanced header tags" );
			}
		}
		
		$offset = 0;
		$loop = true;
		while ( $loop ) {
			$start = strpos ( $plainFile, "<!-- web2printer:start -->", $offset );
			if ($start) {
				$end = strpos ( $plainFile, "<!-- web2printer:end -->", $offset );
				if ($end) {
					$this->content = $this->content . substr ( $plainFile, $start, $end - $start );
				} else {
					die ( "Missing <!-- web2printer:end -->" );
				}
			} else {
				$loop = false;
			}
			$offset = $end + 1;
		} // while
		

		if ($this->clearImages > 0) {
			$this->clearImages ();
		}
		
		if (0 < $this->resolveLink) {
			$this->solveLinks ();
		}
	}
	
	function insertForm($file) {
		
		global $myEMailForm;
		global $form;
		$fp = fopen ( $myEMailForm, "r" );
		$form = fread ( $fp, 64000 );
		return eregi_replace ( "<!-- web2printer:email !-->", $form, $file );
	}
	
	// image processing
	// 0 : leave images
	// 1 : supress image printing
	// 2 : replace images with [IMAGE]
	// 3 : replace images with alt
	

	function clearImages() {

		$offset = 0;
		$this->content = preg_replace ( "/<img$/i", "<img", $this->content );
		
		switch ( $this->clearImages) {
			// leave images
			case 0 :
			break;
			// remove images
			case 1 :
				$this->content = preg_replace ( "/<img([^>]?)*>/i", "", $this->content );
			break;
			// replace images with [IMAGE]
			case 2 :
				$this->content = preg_replace ( "/<img([^>]?)*>/i", "[Image]", $this->content );
			break;
			// replace images with alt
			case 3 :
				while ( $start = strpos ( $this->content, "<img", $offset ) ) {
					$offset = $start + 1;
					$end = strpos ( $content, ">", $offset );
					$entry = substr ( $this->content, $start, $end - $start );
					if (preg_match ( "/alt([^=]?)*=([^\"]?)*\"([^\"]?)*/i", $entry, $regs )) {
						$alt = preg_replace ( "/alt([^=]?)*=([^\"]?)*\"/i", "", $regs [0] );
						$left = substr ( $this->content, 0, $start );
						$right = substr ( $this->content, $end + 1 );
						$subst = "<b>[Image:" . $alt . "]</b>&nbsp;";
						$this->content = $left . $subst;
						$this->content = $this->content . $right;
						$offset = $end + strlen ( $subst );
					}
					$value = "";
				} // while
				$this->content = preg_replace ( "/<img([^>]?)*>/i", "[Image]", $this->content );
			break;
			// generate image crossreference
			case 4 :
				while ( $start = strpos ( $content, "<img", $offset ) ) {
					$offset = $start + 1;
					$end = strpos ( $this->content, ">", $offset );
					$entry = substr ( $this->content, $start, $end - $start );
					if (preg_match ( "/src([^=]?)*=([^\"]?)*\"([^\"]?)*/i", $entry, $regs )) {
						$src = preg_replace ( "/src([^=]?)*=([^\"]?)*\"/i", "", $regs [0] );
						$src = makeUrl ( $src );
						$left = substr ( $this->content, 0, $start );
						$right = substr ( $this->content, $end + 1 );
						$found = false;
						$count = 0;
						// check if we have this image already
						while ( $count < $imageCount ) {
							if (0 == strcmp ( $images [$count], $src )) {
								$found = true;
								break;
							}
							++ $count;
						}
						if (! $found) {
							$images [$imageCount] = $src;
							++ $imageCount;
						}
						$subst = "[IMAGE No:<b>" . ($count + 1) . "</b>]";
						$this->content = $left . $subst;
						$this->content = $this->content . $right;
						$offset = $end + strlen ( $subst );
					}
					$value = "";
				} // while
			break;
			default :
				die ( "bad parameter img !" );
		}
	}
	
	function solveLinks() {
		
		$offset = 0;
		$this->value = "";
		$len = strlen ( $this->content );
		
		$this->content = preg_replace ( "/<a/i", "<a", $this->content );
		$this->content = preg_replace ( "/<\/a/i", "</a", $this->content );
		while ( $start = strpos ( $this->content, "<a", $offset ) ) {
			$offset = $start + 2;
			$end = strpos ( $this->content, "</a", $offset );
			if ($end == false) {
				die ( "html error: missing &lt;/a&gt; starting at:<br>" . substr ( $this->content, $start, 255 ) );
			}
			$entry = substr ( $this->content, $start, $end - $start + 4 );
			if (preg_match ( "/href([^=]?)*=([^\"]?)*\"([^\"]?)*/i", $entry, $regs )) {
				$link = strtolower ( preg_replace ( "/href([^=]?)*=([^\"]?)*\"/i", "", $regs [0] ) );
				if ($this->resolveLink == 2) {
					if ($pos = strpos ( $link, "?" )) {
						$link = substr ( $link, 0, $pos );
					}
				}
				if (0 < strlen ( $link )) {
					if ($this->resolveLink < 3) {
						$count = 0;
						$found = false;
						// check if we have this href already
						while ( $count < $linkCount ) {
							if (0 == strcmp ( $links [$count], $link )) {
								$found = true;
								break;
							}
							++ $count;
						} // while
						if (! $found) {
							$links [$linkCount] = $link;
							++ $linkCount;
						}
						++ $count;
					}
					if (0 == $this->activeLinks) {
						$entry = preg_replace ( "/<a([^>]?)*>/i", "", $entry );
						$entry = preg_replace ( "/<\/a([^>]?)*>/i", "", $entry );
					}
				}
				$left = substr ( $this->content, 0, $start );
				$right = substr ( $this->content, $end );
				if ($this->resolveLink < 3) {
					$this->content = $left . "<b>" . $entry . "[" . $count . "]</b>";
					$this->content = $this->content . $right;
				} else {
					$this->content = $left . $entry . $right;
				}
			
			} // if preg_match
			$offset = $start + strlen ( $entry );
			if ($offset >= $len) {
				break;
			}
		} // while
	}
	
	function getMeta($plainFile) {
		
		$offset = 0;
		$end = 0;
		
		$plainFile = preg_replace ( "/<(:space:)*meta/i", "<meta", $plainFile );
		while ( $start = strpos ( $this->plainFile, "<meta", $offset ) ) {
			$offset = $start + 1;
			$end = strpos ( $plainFile, ">", $offset );
			$this->metaTags [$metaCount] = substr ( $this->plainFile, $start, $end - $start + 1 );
			if (preg_match ( "/<meta(:space:)*name(:space:)*=(:space:)*\"copyright\"/i", $this->metaTags [$this->metaCount] )) {
				$this->copyright = preg_replace ( "/<meta(:space:)name(:space:)*=(:space:)*\"copyright\"(:space:)*content(:space:)*=\"/i", "", $this->metaTags [$this->metaCount] );
				$this->copyright = substr ( $this->copyright, 0, strpos ( $this->copyright, "\"" ) );
			}
			++ $metaCount;
		}
	}
	
	function checklog($address) {
		
		if (! isset ( $REMOTE_ADDR )) {
			$this->ip = getenv ( "REMOTE_ADDR" );
		} else {
			$this->p = $REMOTE_ADDR;
		}
		$retval = true;
		$this->filename = $this->logfile . "/web2printer" . date ( "Ymd" ) . ".log";
		$filearray = @file ( $this->logfile );
		
		if (is_array ( $this->filearray )) {
			$counter = 0;
			$boundary = 0;
			while ( $counter < count ( $filearray ) && $retval == true ) {
				if (eregi ( $ip, $filearray [$counter] )) {
					++ $boundary;
				}
				if ($maxip < $boundary) {
					$retval = false;
					break;
				}
				++ $counter;
			}
		}
		
		if ($retval == true) {
			$fp = @fopen ( $filename, "a" );
			@fputs ( $fp, date ( "d.m.Y h:m:s", time () ) . " ;" . $urlToPrint . " ;" . $from . " ;" . $name . " ;" . $comment . " ;" . $address . " ;" . $ip . "\n" );
			@fclose ( $fp );
		}
		return $retval;
	}
	
	function SendMail() {

		$ok = true;
		if (! eregi ( "^[a-z0-9_.-]+@[a-z0-9_.-]+\.[a-z]+$", trim ( $this->from ) )) {
			$ok = false;
		}
		$tok = strtok ( $this->to, "," );
		$i = 0;
		while ( $tok && $i < 5 ) {
			if (! eregi ( "^[a-z0-9_.-]+@[a-z0-9_.-]+\\.[a-z]+$", trim ( $tok ) )) {
				$ok = false;
			}
			$tok = strtok ( "," );
			$i ++;
		}
		
		// about if the email adresse not valid syntax
		if (! $ok) {
			echo $this->authentyPage;
			return;
		}
		$headers = "From: " . $this->from . "\r\n";
		//specify MIME version 1.0
		$headers .= "MIME-Version: 1.0\r\n";
		//unique boundary
		$boundary = uniqid ( "web2printer" );
		//tell e-mail client this e-mail contains//alternate versions
		$headers .= "Content-Type: multipart/alternative; boundary =" . $boundary . "\r\n\r\n";
		//message to people with clients who don't
		//understand MIME
		$headers .= "This is a MIME encoded message.\r\n\r\n";
		switch ( $this->footer + 2) {
			case 2 :
				$finalfooter = "</table></body></html>";
			break;
			case 3 :
				$finalfooter = "<tr><td><font size=-1><p><hr size=1 noshade>This Page was generated with " . $this->web2printerVersion . " in: " . get_current () . " <a href=http://www.printer-friendly.com>http://www.printer-friendly.com</a><br></font></p></td></tr></table></body></html>";
			break;
			case 5 :
				$finalfooter = "<tr><td><p><hr size=1 noshade>" . $this->customFooter . "</p></td></tr></table></body></html>";
			break;
		}
		//HTML version of message
		$headers .= "--$boundary\r\n" . "Content-Type: text/html; charset=ISO-8859-1\r\nContent-Transfer-Encoding: base64\r\n\r\n";
		
		$body = "<html><head><title>" . $title . "</title></head><body bgcolor=#ffffff>";
		$body .= "<table summary=\"web2printer crossreference\"><tr><td>";
		if (strlen ( $comment ) > 1) {
			$body .= "=============================================================<br>";
			$body .= $comment;
			$body .= "<br>=============================================================<br>";
		}
		$body .= $content;
		$body .= "</tr></td><tr><td><font size=-1>";
		$body .= "<p><hr size=1 noshade>" . $pageUrlHeader . makeUrl ( $urlToPrint ) . "</p>";
		$body .= "</font></tr></td><tr><td><font size=-1>";
		if (0 < $linkCount) {
			$body .= "<p>" . $pageXRefURLHeader . "<br>";
			for($i = 0; $i < $linkCount; $i ++) {
				$link = makeUrl ( $links [$i] );
				$body .= "[" . ($i + 1) . "] <a href=\"" . $link . "\">" . $link . "</a><br>";
			}
			$body .= "</font></tr></td><tr><td><font size=-1>";
		}
		if (strlen ( $copyright ) > 0) {
			$body .= "<p><hr size=1 noshade><i>Copyright:" . $copyright . "</i><br>";
		}
		$body .= $finalfooter;
		$headers .= chunk_split ( base64_encode ( $body ) );
		//send message
		$tok = strtok ( $to, "," );
		$i = 0;
		while ( $tok && $i < 5 ) {
			mail ( $tok, "Your article:" . $title, "", $headers );
			checklog ( $tok );
			$tok = strtok ( "," );
			$i ++;
		}
		
		echo $this->authentyPage;
	}
	
	// print the procceced file
	function display() {
		
		echo "<html><head>";
		
		if (1 == $this->preserveMetaTags) {
			for($i = 0; $i < $this->metaCount; $i ++) {
				echo $this->metaTags [$i];
			}
		}
		
		if ($this->email == 1) {
			echo $this->content;
			return;
		}
		
		if (strlen ( $this->stylesheet ) > 0) {
			echo "<link href=\"" . $this->stylesheet . "\" rel=\"stylesheet\" type=\"text/css\">";
		}
		
		switch ( $this->footer + 3) {
			case 3 :
				$this->finalfooter = "</table></body></html>";
			break;
			case 4 :
				$this->finalfooter = "<tr><td><font size=-1><p><hr size=1 noshade>This Page was generated with " . $this->web2printerVersion . " in: " . get_current () . " <a href='http://www.printer-friendly.com'>http://www.printer-friendly.com</a><br></font></p></td></tr></table></body></html>";
			break;
			case 5 :
				$this->finalfooter = "<tr><td><p><hr size=1 noshade>" . $this->customFooter . "</p></td></tr></table></body></html>";
			break;
		}
		
		echo "<title>" . $this->title;
		echo "</title></head><body bgcolor=#ffffff><table summary='web2printer crossreference'><tr><td>";
		echo $this->content;
		echo "</tr></td><tr><td><font size=-1>";
		$link = makeUrl ( $this->urlToPrint );
		echo "<p><hr size=1 noshade>" . $this->pageUrlHeader . "<a href=\"" . $link . "\">" . $link;
		echo "</a></p></font></tr></td>";
		echo "<tr><td><font size=-1>";
		if (0 < $this->linkCount) {
			echo $this->pageXRefURLHeader . "<br>";
			for($i = 0; $i < $this->linkCount; $i ++) {
				$link = makeUrl ( $this->links [$i] );
				echo "[" . ($i + 1) . "] <a href=\"" . $link . "\">" . $link . "</a><br>";
			}
			echo "</font></tr></td><tr><td><font size=-1>";
		}
		if (0 < $this->imageCount) {
			echo "<p><b>Images:</b><br>";
			for($i = 0; $i < $this->imageCount; $i ++) {
				echo "[" . ($i + 1) . "] " . makeUrl ( $this->images [$i] ) . "<br>";
			}
		}
		
		echo "</font></tr></td>";
		if (strlen ( $this->copyright ) > 0) {
			echo "<tr><td><font size=-1><p><hr size=1 noshade><i>Copyright:" . $this->copyright . "</i><br></font></tr></td>";
		}
		echo $this->finalfooter;
	}
	?>
